package com.penghk.springbootdemo;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class TaskExecutionWebServer {

    private static final int numThreads = 100;
    private static final int capacity = 100;

    // 使用的LinkedBlockingQueue 会堆积大量请求 OOM
    private static final Executor ex = Executors.newFixedThreadPool(numThreads);
    private static final Executor ex1 = new ThreadPoolExecutor(numThreads, numThreads,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(capacity));

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8088);
        System.out.println("start server");
        while (true) {
            final Socket socket = serverSocket.accept();
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    handleRequest(socket);
                }
            };
            ex1.execute(runnable);
        }
    }

    private static void handleRequest(Socket socket) {
        System.out.println("hello "+socket.getInetAddress().toString());
        try {
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(22);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }
}
